package handlers

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"minipromgr/internal/database"
	"minipromgr/internal/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 全局上传路径变量
var UploadsPath = "uploads"

// SetUploadsPath 设置上传路径
func SetUploadsPath(path string) {
	UploadsPath = path
}

func UploadImage(c *gin.Context) {
	// 支持多文件上传
	form, err := c.MultipartForm()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请选择图片文件"})
		return
	}
	defer form.RemoveAll()

	files := form.File["images"]
	if len(files) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请选择图片文件"})
		return
	}

	// 创建上传目录
	if err := os.MkdirAll(UploadsPath, 0755); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建上传目录失败"})
		return
	}

	var uploadedPictures []models.Picture
	var filenames []string

	for _, header := range files {
		// 检查文件类型
		contentType := header.Header.Get("Content-Type")
		if !strings.HasPrefix(contentType, "image/") {
			continue // 跳过非图片文件
		}

		// 生成唯一文件名
		ext := filepath.Ext(header.Filename)
		filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
		filePath := filepath.Join(UploadsPath, filename)

		// 保存文件
		if err := c.SaveUploadedFile(header, filePath); err != nil {
			continue // 跳过保存失败的文件
		}

		// 保存到数据库
		picture := models.Picture{
			Filename:     filename,
			OriginalName: header.Filename,
			FilePath:     filePath,
		}

		if err := database.DB.Create(&picture).Error; err != nil {
			continue // 跳过数据库保存失败的文件
		}

		uploadedPictures = append(uploadedPictures, picture)
		filenames = append(filenames, filename)
	}

	if len(uploadedPictures) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "没有成功上传任何图片"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message":   "上传成功",
		"pictures":  uploadedPictures,
		"filenames": filenames,
	})
}

func GetImage(c *gin.Context) {
	filename := c.Param("filename")
	filePath := filepath.Join(UploadsPath, filename)

	// 检查文件是否存在
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		c.JSON(http.StatusNotFound, gin.H{"error": "图片不存在"})
		return
	}

	c.File(filePath)
}

func DeleteImage(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid image ID"})
		return
	}

	db := models.GetDB()
	var picture models.Picture
	if err := db.First(&picture, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "Image not found"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch image"})
		}
		return
	}

	// 删除文件
	if err := os.Remove(picture.FilePath); err != nil {
		// 文件删除失败，但继续删除数据库记录
		fmt.Printf("Warning: Failed to delete file %s: %v\n", picture.FilePath, err)
	}

	// 删除数据库记录
	if err := db.Delete(&picture).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete image record"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Image deleted successfully"})
}
